<template>
  <div class="energy-common">
    <div class="common-bg-title">工序电耗</div>
    <div class="main">
      <div class="title">数据趋势</div>
      <div v-loading="loading">
        <el-row type="flex" class="mb15">
          <time-picker
            type="datetimerange"
            :format="['YYYY-MM-DD 00:00:00', 'YYYY-MM-DD 23:59:59']"
            @getTime="getTime"
          ></time-picker>
        </el-row>

        <div class="bar-chart">
          <el-radio-group
            class="toggle-chart"
            v-model="type"
            size="mini"
            fill="#2c67f6"
            text-color="#fff"
          >
            <el-radio-button label="bar">
              <svg-icon icon-class="bar" />
            </el-radio-button>
            <el-radio-button label="line"
              ><svg-icon icon-class="line"/></el-radio-button
          ></el-radio-group>
          <div
            v-show="type == 'bar'"
            ref="chart1"
            class="mb10"
            style="width:100%;height:100%"
          ></div>
          <div
            v-show="type == 'line'"
            ref="chart2"
            class="mb10"
            style="width:100%;height:100%"
          ></div>
        </div>

        <div class="common-table" ref="table">
          <el-table :data="tableData" style="width: 100%">
            <el-table-column label="序号" width="55" align="center">
              <template slot-scope="{ row, column, $index }">
                {{ parseInt($index) + 1 }}
              </template>
            </el-table-column>
            <el-table-column
              prop="gongxu"
              label="工序"
              align="center"
              min-width="10%"
            />
            <el-table-column
              prop="sumImpEp"
              label="电耗"
              align="center"
              min-width="10%"
            />
            <el-table-column
              prop="time"
              min-width="15%"
              label="时间"
              align="center"
            ></el-table-column>
          </el-table>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import TimePicker from '@/components/TimePicker';
import { getGxChart, getGxLine } from '@/api/energy';
export default {
  components: {
    TimePicker
  },
  data() {
    return {
      type: 'bar',
      tableHeight: 200,
      search: {
        startTime: '',
        endTime: ''
      },
      time: [],
      timeText: '',
      loading: false,
      searchRules: {},
      tableData: [],
      total: 10,
      chart1: null,
      chart2: null
    };
  },
  watch: {
    time: function(val) {
      this.search.startTime = val ? val[0] : '';
      this.search.endTime = val ? val[1] : '';
      this.timeText = val ? val.join('~') : '';
      this.getChart();
      this.getLine();
    },
    type: function(val) {
      this.$nextTick(() => {
        this.chart2.resize();
        this.chart2.resize();
      });
    }
  },
  computed: {
    bcOption() {
      return this.$store.getters.bcOption;
    },
    gxOption() {
      return this.$store.getters.gxOption;
    }
  },
  methods: {
    async getChart() {
      this.loading = true;
      let form = this.$_.pick(this.search, ['startTime', 'endTime']);
      const res = await getGxChart(form);
      if (res.code == 1) {
        let { data } = res;
        this.tableData = data;
        let chartData = {
          xAxis: [],
          yAxis: []
        };
        data.map(item => {
          chartData.xAxis.push(item.gongxu);
          chartData.yAxis.push(item.sumImpEp);
        });
        this.setBarChart(chartData);
        this.loading = false;
      }
    },
    async getLine() {
      const res = await getGxLine(this.search);
      if (res.code == 1) {
        let { data } = res;
        let arr = this.formatterArr(data, 'gongxu');
        let chartData = { time: [], series: [], gongxu: [] };
        chartData.time = arr[0]['data'].map(item => {
          return item.time;
        });
        chartData.gongxu = arr.map(item => {
          return item.gongxu;
        });
        arr.map(item => {
          let obj = { name: item['gongxu'], type: 'line' };
          obj.data = item.data.map(c => {
            return c.sImpEp;
          });
          chartData.series.push(obj);
        });
        this.setLineChart(chartData);
      }
    },
    setBarChart(data) {
      this.chart1 = this.$echarts.init(this.$refs.chart1);
      let option = {
        grid: {
          left: '5%',
          right: '2%'
        },
        tooltip: {
          trigger: 'axis',
          textStyle: {
            fontSize: 13
          },
          padding: 10,
          backgroundColor: 'rgba(66, 66, 89, 0.8)',
          formatter: function(params) {
            var result =
              '<div style="font-size:14px;font-weight:600;margin-bottom:4px">' +
              params[0].axisValue +
              '</div>';
            result +=
              '<span style="display:inline-block;margin-right:5px;border-radius:10px;width:9px;height:9px;background-color:' +
              params[0].color +
              '"></span>';
            result += params[0].axisValue + '：' + params[0].data + 'kw·h';
            return result;
          }
        },
        xAxis: {
          type: 'category',
          data: data.xAxis,
          axisTick: { show: false },
          axisLine: { lineStyle: { color: 'rgba(225,231,235)' } },
          axisLabel: { color: '#606D86' }
        },
        yAxis: {
          type: 'value',
          name: '单位：kw·h',
          nameTextStyle: { color: '#292B3D' },
          axisLine: { show: false },
          axisTick: { show: false },
          axisLabel: { color: '#606D86' },
          splitLine: {
            lineStyle: {
              type: 'dotted',
              color: 'rgba(65, 97, 128, 0.15)'
            }
          }
        },
        series: [
          {
            data: data.yAxis,
            type: 'bar',
            barWidth: 25,
            color: '#5B8FF9'
          }
        ]
      };
      this.chart1.setOption(option);
      var _this = this;
      window.addEventListener('resize', function() {
        _this.chart1.resize();
      });
    },
    setLineChart(data) {
      this.chart2 = this.$echarts.init(this.$refs.chart2);
      let option = {
        tooltip: {
          trigger: 'axis',
          textStyle: {
            fontSize: 13
          },
          padding: 10,
          backgroundColor: 'rgba(66, 66, 89, 0.8)',
          formatter: function(c) {
            let str =
              '<div style="font-size:14px;font-weight:600;margin-bottom:4px">' +
              c[0]['name'] +
              '</div>';
            c.forEach(item => {
              str +=
                item.marker +
                item.seriesName +
                '<span style="display:inline-block;width:10px;height:10px;"></span>' +
                ': ' +
                item.value +
                'kw·h' +
                '<br />';
            });
            return str;
          }
        },
        legend: {
          left: '5%',
          icon: 'circle',
          itemWidth: 12,
          data: data.gongxu
        },
        color: [
          '#4C85FF',
          '#61DDAA',
          '#8061EF',
          '#FFC403',
          '#F2693E',
          '#A9A9A9',
          '#FFB6C1',
          '#DC143C',
          '#3CB371',
          'rgb(234,124,204)',
          '#87CEEB'
        ],
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        toolbox: {
          feature: {
            saveAsImage: {}
          }
        },
        xAxis: {
          type: 'category',
          data: data.time,
          axisTick: { show: false },
          axisLine: { lineStyle: { color: 'rgba(225,231,235)' } },
          axisLabel: { color: '#606D86' }
        },
        yAxis: [
          {
            type: 'value',
            name: '单位：kw·h',
            nameLocation: 'end',
            nameTextStyle: { color: '#292B3D' },
            axisTick: { show: false },
            axisLine: {
              show: true,
              lineStyle: { color: 'rgb(219,225,231)' }
            },
            axisLabel: {
              show: true,
              fontSize: 13,
              textStyle: {
                color: '#292B3D'
              }
            },
            splitLine: {
              lineStyle: {
                color: '#EAEBF0',
                type: 'dotted'
              }
            }
          }
        ],
        series: data.series
      };
      this.chart2.setOption(option);
      var _this = this;
      window.addEventListener('resize', function() {
        _this.chart2.resize();
      });
    },
    formatterArr(arr, group_key) {
      let map = {};
      let res = [];
      for (let i = 0; i < arr.length; i++) {
        let ai = arr[i];
        if (!map[ai[group_key]]) {
          map[ai[group_key]] = [ai];
        } else {
          map[ai[group_key]].push(ai);
        }
      }
      Object.keys(map).forEach(key => {
        res.push({ data: map[key], gongxu: key });
      });
      return res;
    },
    getTime(val) {
      this.time = val;
    }
  }
};
</script>

<style lang="stylus" scoped>
.common-wrapper {
  height: 100%;
}

.common-search {
  display: flex;

  ::v-deep .btn-list .el-form-item__content {
    display: flex;
  }
}
</style>
